<template>
  <view class="register-container">
    <!-- 活动信息 -->
    <view class="activity-info">
      <view class="activity-title">{{ activity.name }}</view>
      <view class="activity-desc">{{ activity.description }}</view>
      <view class="activity-time">{{ formatDateTime(activity.startTime) }} - {{ formatDateTime(activity.endTime) }}</view>
      <view class="activity-location">{{ activity.location || '待定' }}</view>
    </view>
    
    <!-- 报名表单 -->
    <view class="register-form">
      <view class="form-item">
        <text class="form-label">选择就诊人：</text>
        <picker 
          :value="selectedPatientIndex" 
          :range="patientList" 
          range-key="name"
          @change="onPatientChange"
        >
          <view class="picker-value">
            {{ selectedPatient ? selectedPatient.name : '请选择就诊人' }}
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">备注信息：</text>
        <textarea 
          v-model="remark" 
          placeholder="请输入备注信息（可选）"
          class="remark-input"
        ></textarea>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-section">
      <button 
        class="submit-btn" 
        type="primary" 
        @click="submitRegistration"
        :disabled="!selectedPatient || submitting"
      >
        {{ submitting ? '提交中...' : '确认报名' }}
      </button>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ActivityRegister',
  data() {
    return {
      activityId: null,
      activity: {},
      patientList: [],
      selectedPatientIndex: -1,
      selectedPatient: null,
      remark: '',
      submitting: false
    }
  },
  
  onLoad(options) {
    this.activityId = options.activityId;
    this.loadActivityDetail();
    this.loadPatientList();
  },
  
  methods: {
    // 加载活动详情
    async loadActivityDetail() {
      try {
        const response = await uni.request({
          url: this.$baseUrl + `/activity/${this.activityId}`,
          method: 'GET',
          header: {
            'Content-Type': 'application/json'
          }
        });
        
        if (response.statusCode === 200 && response.data.code === 200) {
          this.activity = response.data.data;
        } else {
          uni.showToast({
            title: response.data.message || '获取活动详情失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取活动详情失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    
    // 加载就诊人列表
    async loadPatientList() {
      try {
        const token = uni.getStorageSync('token');
        if (!token) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }, 1500);
          return;
        }
        
        const response = await uni.request({
          url: this.$baseUrl + '/patient/list',
          method: 'GET',
          header: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
          }
        });
        
        if (response.statusCode === 200 && response.data.code === 200) {
          this.patientList = response.data.data || [];
        } else {
          uni.showToast({
            title: response.data.message || '获取就诊人列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取就诊人列表失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    
    // 选择就诊人
    onPatientChange(e) {
      this.selectedPatientIndex = e.detail.value;
      this.selectedPatient = this.patientList[this.selectedPatientIndex];
    },
    
    // 提交报名
    async submitRegistration() {
      if (!this.selectedPatient) {
        uni.showToast({
          title: '请选择就诊人',
          icon: 'none'
        });
        return;
      }
      
      // 检查用户是否已登录
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }, 1500);
        return;
      }
      
      this.submitting = true;
      try {
        const response = await uni.request({
          url: this.$baseUrl + '/activity-registration/register',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
          },
          data: {
            activityId: this.activityId,
            patientId: this.selectedPatient.id,
            remark: this.remark
          }
        });
        
        if (response.statusCode === 200 && response.data.code === 200) {
          uni.showToast({
            title: '报名成功',
            icon: 'success'
          });
          
          // 跳转到我的预约页面
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/profile/profile'
            });
          }, 1500);
        } else {
          uni.showToast({
            title: response.data.message || '报名失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('报名失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px;
}

.activity-info {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 10px;
}

.activity-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.activity-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 10px;
}

.activity-time, .activity-location {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.register-form {
  background-color: #fff;
  padding: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.picker-value {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  background-color: #f9f9f9;
}

.remark-input {
  width: 100%;
  height: 80px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background-color: #f9f9f9;
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.submit-btn {
  width: 100%;
  height: 44px;
  border-radius: 22px;
  font-size: 16px;
}
</style> 